package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.user.IUserLoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.converter.UserConverterMapper;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.MemberJson;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.AESUtil;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.log4j.Log4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @program: project3-group12
 * @description:
 * @author: YuHui
 * @create: 2021-08-25 20:59
 **/

@Service
@Log4j
public class LoginServiceImpl implements IUserLoginService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserConverterMapper userConverterMapper;

    @Autowired
    MemberConverter memberConverter;

    /**
     * 校验token是否合法
     *
     * @param checkAuthRequest
     * @return
     */
    @Override
    public CheckAuthResponse validToken(CheckAuthRequest checkAuthRequest) {

        CheckAuthResponse checkAuthResponse = new CheckAuthResponse();

        try {
            String token = checkAuthRequest.getToken();
            String username = JwtTokenUtils.builder().token(token).build().freeJwt();

            Member member = new Member();
            member.setUsername(username);
            Member member1 = memberMapper.selectOne(member);

            MemberJson memberJson = new MemberJson();
            memberJson.setUid(member1.getId());
            memberJson.setUserName(username);
            String json = JSON.toJSONString(memberJson);

            //token合法
            checkAuthResponse.setUserinfo(json);
            checkAuthResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("LoginServiceImpl validToken occur " + e);
            checkAuthResponse.setCode(SysRetCodeConstants.USER_INFOR_INVALID.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.USER_INFOR_INVALID.getMessage());
        }

        return checkAuthResponse;
    }

    /**
     * 登陆
     *
     * @param userLoginRequest
     * @return
     */
    @Override
    public UserLoginResponse Login(UserLoginRequest userLoginRequest) {

        UserLoginResponse userLoginResponse = new UserLoginResponse();

        try {
            //校验参数
            userLoginRequest.requestCheck();

            Member member = new Member();

            //根据登录信息拿到用户名
            member.setUsername(userLoginRequest.getUserName());

            //根据登录信息拿到密码，并进行加密
            String password = userLoginRequest.getPassword();
            String encrypt = new AESUtil(password).encrypt();
            member.setPassword(encrypt);
            member.setIsVerified("Y");
            //根据用户信息查询用户
            Member member1 = memberMapper.selectOne(member);

            //查询login的信息
            if (member1 == null) {
                userLoginResponse.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
                userLoginResponse.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
                return userLoginResponse;
            }
            //走到这里，说明用户信息不为空,获取token
            String token = JwtTokenUtils.builder().msg(member.getUsername()).build().creatJwtToken();

            //将token和code,message作为信息 返回出去
            userLoginResponse = memberConverter.member2LoginRes(member1);
            userLoginResponse.setToken(token);
            userLoginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("login occur exception " + e);
            userLoginResponse.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());

        }
        return userLoginResponse;
    }


    /**
     * 验证登录，查询login的信息
     *
     * @param userGetLoginRequest
     * @return
     */
    @Override
    public UserGetLoginResponse checklogin(UserGetLoginRequest userGetLoginRequest) {
        UserGetLoginResponse userGetLoginResponse = new UserGetLoginResponse();

        try {
            //参数校验
            userGetLoginRequest.requestCheck();
            //根据用户姓名查找用户
            String userinfo = userGetLoginRequest.getUserinfo();
            JSONObject object = JSON.parseObject(userinfo);
            String userName = object.get("userName").toString();
            Member member = new Member();
            member.setUsername(userName);
            Member member1 = memberMapper.selectOne(member);

            //如果查询不到用户的数据，返回用户信息不合法的代码和信息
            if (member1 == null) {
                userGetLoginResponse.setFile(SysRetCodeConstants.USER_INFOR_INVALID.getCode());
                userGetLoginResponse.setMsg(SysRetCodeConstants.USER_INFOR_INVALID.getMessage());
            } else {
                //如果查询到了用户的数据
                userGetLoginResponse = userConverterMapper.userGetLoginInfos(member1);
                userGetLoginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
                userGetLoginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            }

        } catch (Exception e) {
            log.error("LoginServiceImpl.login occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(userGetLoginResponse, e);
        }
        return userGetLoginResponse;
    }
}